package com.github.jave.process;

import java.util.ArrayList;
import java.util.List;

public class ExecProcess {

    private List<ProcessListener> processListeners = new ArrayList<ProcessListener>();
    private Runtime runtime;
    private ExecProcess(){
        runtime = Runtime.getRuntime();
    }

    /**
     * 利用静态内部类的特性 实现单例，代码简单 线程安全
     */
    private static class ExecProcessInstance{
        private static final ExecProcess me = new ExecProcess();
    }

    public static ExecProcess getInstance(){
        return ExecProcessInstance.me;
    }

    /**
     * 同步执行命令
     * @param cmd 待执行命令
     * @return 0 成功  1失败
     */
    public int execSync(String cmd){
        try {
            Process process = exec(cmd);

            process.waitFor();

            //notifyResult(process);
            new NotifyProcess(process,this.processListeners).run();
            return process.exitValue();
        }catch (Exception e){
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * 异步执行命令
     * @param cmd 待执行命令
     */
    public void execAsync(String cmd){
        try {
            Process process = exec(cmd);

            new NotifyProcess(process,this.processListeners).run();

            //notifyResult(process);

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private Process exec(String cmd) throws Exception {
        Process process = runtime.exec(cmd);
        runtime.addShutdownHook(new KillProcess(process));
        return  process;
    }

    public void addListener(ProcessListener listener){
        processListeners.add(listener);
    }
    public void removeListener(ProcessListener listener){
        processListeners.remove(listener);
    }
    public void removeAllListener(){
        processListeners.clear();
    }

}
